﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using CLEX.AdminUI.Service;
using CLEX.AdminUI.ViewModel;

namespace CLEX.AdminUI.Services
{
    internal sealed class WindowService
    {
        private readonly Dictionary<ViewModelBase, Window> vmToWindow = new Dictionary<ViewModelBase, Window>();
        private readonly Dictionary<Window, ViewModelBase> windowToVm = new Dictionary<Window, ViewModelBase>();
        private readonly object sync = new object();

        private void Add(ViewModelBase vm, Window window)
        {
            lock (sync)
            {
                vmToWindow.Add(vm, window);
                windowToVm.Add(window, vm);
            }
        }

        private bool Remove(ViewModelBase vm)
        {
            lock (sync)
            {
                if (vmToWindow.ContainsKey(vm))
                {
                    var window = vmToWindow[vm];
                    vmToWindow.Remove(vm);
                    windowToVm.Remove(window);
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        private bool Remove(Window window)
        {
            lock (sync)
            {
                if (windowToVm.ContainsKey(window))
                {
                    var vm = windowToVm[window];
                    vmToWindow.Remove(vm);
                    windowToVm.Remove(window);
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public void CloseWindow(ViewModelBase viewModel)
        {
            Window window;
            lock (sync)
            {
                vmToWindow.TryGetValue(viewModel, out window);
            }
            if (window != null)
            {
                window.Close();
            }
        }

        public void ShowWindow(ViewModelBase viewModel, Window window)
        {
            Add(viewModel, window);
            window.Closed += Window_Closed;
            window.Show();
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            if (Remove((Window)sender))
            {
                ((Window)sender).Closed -= Window_Closed;
            }
        }
    }
}
